﻿using DocumentFormat.OpenXml.Spreadsheet;
using Google.ProtocolBuffers;
using LightingServer;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ImportMoudel
{
    public class BuilderCreator
    {
        public object Create(TableRef tableRef, IList<string> data)
        {
            try
            {
                object instance = Activator.CreateInstance(tableRef.ClassType);

                MethodInfo idMethodInfo = tableRef.ClassType.GetMethod("SetId");
                idMethodInfo.Invoke(instance, new object[] { Guid.NewGuid().ToString().ToUpper() });

                foreach (ColRef colRef in tableRef.RefList)
                {
                    try
                    {
                        MethodInfo methodInfo = tableRef.ClassType.GetMethod(colRef.CallMethod);
                        string value = data[colRef.Index];
                        if (string.IsNullOrEmpty(value))
                        {
                            continue;
                        }

                        if (colRef.IsRef)
                        {
                            ResItem resItem = ResourceProvider.GetResItem(colRef.Guid, value);
                            methodInfo.Invoke(instance, new object[] { resItem.ItemID });
                        }
                        else
                        {
                            ParameterInfo[] parameterInfo = methodInfo.GetParameters();
                            Type type = parameterInfo[0].ParameterType;
                            try
                            {
                                if (type == typeof(System.String))
                                {
                                    methodInfo.Invoke(instance, new object[] { value });
                                }
                                else if (type == typeof(System.UInt32))
                                {
                                    uint uintValue;
                                    if (uint.TryParse(value, out uintValue))
                                    {
                                        methodInfo.Invoke(instance, new object[] { uintValue });
                                    }

                                }
                                else if (type == typeof(System.Double))
                                {
                                    double doubleValue;
                                    if (double.TryParse(value, out doubleValue))
                                    {
                                        methodInfo.Invoke(instance, new object[] { doubleValue });
                                    }
                                }
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return instance;
            }
            catch
            {
            }
            return null;
        }
    }

    public enum PictureType
    {
        PNG = 1,
        BMP = 2,
        JPG = 3,
        GIF = 4
    }

    public class PictureCreator
    {
        private static Dictionary<string, PictureType> _pictureTypes;

        static PictureCreator()
        {
            _pictureTypes = new Dictionary<string, PictureType>();
            _pictureTypes["png"] = PictureType.PNG;
            _pictureTypes["bmp"] = PictureType.BMP;
            _pictureTypes["jpg"] = PictureType.JPG;
            _pictureTypes["jpeg"] = PictureType.JPG;
            _pictureTypes["gif"] = PictureType.GIF;
        }

        private DirectoryInfo _forder;

        public PictureCreator()
        {
            string newForder = Path.Combine(LightingServerContext.ImageRoot, DateTime.Now.ToString("yyyyMMddHHmmss"));
            _forder = Directory.CreateDirectory(newForder);
        }

        private byte[] BmpToPNG(byte[] stream)
        {
            Image img = Image.FromStream(new MemoryStream(stream));
            byte[] arr = null;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, ImageFormat.Png);
                arr = ms.ToArray();
            }

            return arr;
        }


        public object Create(TableRef tableRef, IList<string> data, string prefixKey, IImageProvider provider)
        {
            try
            {
                object instance = Activator.CreateInstance(tableRef.ClassType);

                MethodInfo idMethodInfo = tableRef.ClassType.GetMethod("SetId");
                idMethodInfo.Invoke(instance, new object[] { Guid.NewGuid().ToString().ToUpper() });

                foreach (ColRef colRef in tableRef.RefList)
                {
                    try
                    {
                        ImageFile imageFile = provider.GetImageFileByKey(string.Format("{0}{1}", prefixKey, colRef.Index + 1));
                        if (imageFile != null)
                        {
                            int extStartIndex = imageFile.Name.LastIndexOf('.');
                            string ext = imageFile.Name.Substring(extStartIndex + 1).ToLower();
                            string prefixName = imageFile.Name.Substring(0, extStartIndex);

                            string localName = imageFile.Name;
                            if (ext == "bmp")
                            {
                                using (MemoryStream ms = new MemoryStream(imageFile.File))
                                {
                                    Image bmpImage = Image.FromStream(ms);
                                    localName = prefixName + ".jpg";
                                    bmpImage.Save(Path.Combine(_forder.FullName, localName), ImageFormat.Jpeg);
                                }
                            }
                            else
                            {
                                using (FileStream fs = File.Create(Path.Combine(_forder.FullName, localName)))
                                {
                                    fs.Write(imageFile.File, 0, imageFile.File.Length);
                                    fs.Flush();
                                }
                            }
                            
                            MethodInfo methodInfo = tableRef.ClassType.GetMethod(colRef.CallMethod);
                            methodInfo.Invoke(instance, new object[] { _forder.Name + "/" +  localName });
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return instance;
            }
            catch
            {
            }
            return null;
        }
    }
}
